package com.zl.tby.service.impl;

import com.zl.tby.core.base.bean.TbyPageResult;
import com.zl.tby.core.base.util.ToolsUtil;
import com.zl.tby.core.common.R;
import com.zl.tby.dto.TbyJointDefenceQuery;
import com.zl.tby.model.TbyJointDefence;
import com.zl.tby.repository.TbyJointDefenceRepo;
import com.zl.tby.service.ITbyJointDefenceService;
import com.zl.tby.vo.TbyJointDefenceForm;
import org.noear.solon.annotation.Component;
import org.noear.solon.data.annotation.Tran;
import org.noear.wood.DbContext;
import org.noear.wood.IPage;
import org.noear.wood.annotation.Db;
import org.noear.wood.utils.StringUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 联防联控接口实现类
 * @author sunjiaxing
 * @version 1.0
 * @since 2024/8/22 00:23
 */
@Component
public class TbyJointDefenceServiceImpl implements ITbyJointDefenceService {

    @Db
    private TbyJointDefenceRepo tbyJointDefenceRepo;
    @Db
    private DbContext db;

    @Override
    @Tran
    public R<TbyJointDefence> add(TbyJointDefenceForm form) {
        TbyJointDefence entity = form.createEntity();
        entity.setCreateBy(ToolsUtil.getLoginUserId());
        entity.setCreateTime(LocalDateTime.now());
        long id = tbyJointDefenceRepo.insert(entity, true);
        entity.setId(id);
        return R.ok(entity);
    }

    @Override
    @Tran
    public R<TbyJointDefence> update(TbyJointDefenceForm form) {
        TbyJointDefence entity = this.get(form.getId());
        if (entity == null) {
            return R.failed("数据不存在");
        }
        form.updateEntity(entity);
        entity.setUpdateBy(ToolsUtil.getLoginUserId());
        entity.setUpdateTime(LocalDateTime.now());
        tbyJointDefenceRepo.updateById(entity, false);
        return R.ok(entity);
    }

    @Override
    public R<Void> delete(Long id) {
        int flag = tbyJointDefenceRepo.deleteById(id);
        return flag > 0 ? R.ok() : R.failed("删除失败");
    }

    @Override
    public TbyJointDefence get(Long id) {
        return tbyJointDefenceRepo.selectById(id);
    }

    @Override
    public TbyPageResult<TbyJointDefence> page(TbyJointDefenceQuery query) {
        IPage<TbyJointDefence> iPage = tbyJointDefenceRepo.selectPage(query.getOffset(), query.getSize(), mp -> {
            mp.whereTrue()
                    .andIf(StringUtils.isNotEmpty(query.getTitle()), "title like ?", "%" + query.getTitle() + "%")
                    .andIf(ToolsUtil.isNotNull(query.getType()), "type = ?", query.getType())
                    .andIf(ToolsUtil.isNotNull(query.getPublish()), " publish = ?", query.getPublish());
            if (StringUtils.isNotEmpty(query.getOrder())) {
                mp.orderBy(query.getOrder());
            }
        });
        iPage.getList().forEach(item -> {
            item.setCreateTimeFormat(item.getCreateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        });
        return new TbyPageResult(iPage, query);
    }

    @Override
    public List<TbyJointDefence> list(TbyJointDefenceQuery query) {
        return tbyJointDefenceRepo.selectList(mp -> {
            mp.whereTrue()
                    .andIf(StringUtils.isNotEmpty(query.getTitle()), "title like ?", "%" + query.getTitle() + "%")
                    .andIf(ToolsUtil.isNotNull(query.getType()), "type = ?", query.getType())
                    .andIf(ToolsUtil.isNotNull(query.getPublish()), " publish = ?", query.getPublish())
                    .andIf(ToolsUtil.isNotNull(query.getExcludeId()), " id != ?", query.getExcludeId());
            if (StringUtils.isNotEmpty(query.getOrder())) {
                mp.orderBy(query.getOrder());
            }
        });
    }

    @Override
    public R<Void> release(Long id, Integer publish) {
        TbyJointDefence entity = this.get(id);
        if (entity != null) {
            if (publish.intValue() == 1) {
                // 上架操作，需要验证是否已经存在上架的
                try {
                    long count = db.table("tby_joint_defence").whereEq("type", entity.getType()).andEq("publish", 1).andNeq("id", entity.getId()).selectCount();
                    if (count > 0) {
                        return R.failed("该类型下已存在上架的信息");
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            entity.setPublish(publish);
            entity.setUpdateBy(ToolsUtil.getLoginUserId());
            entity.setUpdateTime(LocalDateTime.now());
            tbyJointDefenceRepo.updateById(entity, false);
            return R.ok();
        }
        return R.failed("数据不存在");
    }
}
